import { Button, InputNumber, Input, Switch, Row, Col, Tooltip, message, Select } from 'antd';

import { CQXG_STATE, LRKPB_STATE, renderOverflowText } from '../common/Format';

import pageStyles from '@/common/pageLayout.less';
import { PlusCircleOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
import { UploadFormCommon } from '../common/UploadForm';
import MyIcon from '@/components/MyIcon';
import { downloadTemplate, getFileNameNotType, splitFileUrl } from '@/utils';
import { ColumnsRenderFun, formatDecimal } from '../../Acommon';

const formatDecimals = (val: any) => {
  // 不存在的话就返回'--'
  if (!val) return '0.00';
  // 将输入值转为数字，以确保处理的是数值类型
  const num = Number(val);
  // 如果转换后的数值是NaN，则直接返回原始值
  if (isNaN(num)) return '0.00';
  // 使用toFixed方法确保小数点后有两位，然后再转回字符串
  return num.toFixed(2) + '';
};

/**
 * @getSupplierTableColumns 供应商列表
 * @returns
 */
export const getSupplierTableColumns = ({
  onAdd,
  onDelete,
  openSupplier,
  changeBidder,
  onEditTable,
  SourceState,
  isShowOpenBtn,
}: any): Record<string, any>[] => {
  let columnsList = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      fixed: 'left',
      width: 90,
      visible: true,
      align: 'center',
      render: (_: string, __: Record<string, any>, index: string) => index + 1,
    },
    {
      title: (
        <>
          <MyIcon type="icon-edit1" style={{ marginRight: '.5rem' }} />
          单位名称
        </>
      ),
      dataIndex: 'fullName',
      key: 'fullName',
      width: 200,
      visible: true,
      fixed: 'left',
      render: (text: string, record: Record<string, any>, index: number) => {
        return (
          <Row>
            <Col span={record?.id ? 24 : 20}>
              {text ? (
                <Tooltip title={text || undefined}>
                  <span className={pageStyles['over-flow-hidden']}>{text}</span>
                </Tooltip>
              ) : (
                <span
                  style={{ color: '#ccc' }}
                  className={'supplier-selectFull'}
                  // onClick={() => {
                  //   if (!record?.id && isShowOpenBtn) {
                  //     openSupplier(index);
                  //   }
                  // }}
                >
                  请选择企业
                </span>
              )}
            </Col>
            {record?.id ? null : (
              <Col span={4}>
                <a
                  onClick={() => {
                    if (isShowOpenBtn && (SourceState == CQXG_STATE() || SourceState == LRKPB_STATE()) && !record?.id) {
                      openSupplier(index);
                    }
                  }}
                >
                  <SearchOutlined />
                </a>
              </Col>
            )}
          </Row>
        );
      },
    },
    {
      title: (
        <>
          <MyIcon type="icon-edit1" style={{ marginRight: '.5rem' }} />
          是否联合体
        </>
      ),
      dataIndex: 'complexFlag',
      key: 'complexFlag',
      width: 140,
      visible: true,
      render: (text: number = 0, record: Record<string, any>, index: number) => {
        return (
          <Switch
            checkedChildren="是"
            unCheckedChildren="否"
            checked={Boolean(text)}
            defaultChecked={Boolean(text)}
            disabled={!!record?.id || !isShowOpenBtn}
            onChange={(checked) => {
              onEditTable({ value: Number(checked), key: 'complexFlag', type: 'Check', record, index });
            }}
          />
        );
      },
    },
    {
      title: (
        <>
          <MyIcon type="icon-edit1" style={{ marginRight: '.5rem' }} />
          联合体成员
        </>
      ),
      dataIndex: 'complexNames',
      key: 'complexNames',
      width: 230,
      visible: true,
      render: (text: string, record: Record<string, any>, index) => {
        // 需要判断该数据是否checked = true是否联合体
        if (record?.complexFlag) {
          return (
            <Input
              placeholder="请以逗号隔开"
              defaultValue={text}
              value={text}
              disabled={!!record?.id || !isShowOpenBtn}
              onChange={(en) => {
                onEditTable({ value: en?.target?.value, key: 'complexNames', type: 'Input', record, index });
              }}
            />
          );
        } else {
          return '暂无成员';
        }
      },
    },
    {
      title: (
        <>
          <MyIcon type="icon-edit1" style={{ marginRight: '.5rem' }} />
          推荐中标人
        </>
      ),
      dataIndex: 'selectFlag',
      key: 'selectFlag',
      width: 160,
      visible: true,
      render: (text: string, _: Record<string, any>, index: number) => {
        return (
          <Switch
            checkedChildren="是"
            unCheckedChildren="否"
            onChange={(value) => changeBidder(value, index)}
            disabled={!isShowOpenBtn}
            checked={Boolean(text)}
          />
        );
      },
    },
    {
      title: (
        <>
          <MyIcon type="icon-edit1" style={{ marginRight: '.5rem' }} />
          报价类型
        </>
      ),
      dataIndex: 'quotationType',
      key: 'quotationType',
      width: 160,
      visible: true,
      render: (text, record: Record<string, any>, index) => {
        return (
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            {!isShowOpenBtn ? (
              text == 0 ? (
                '总价'
              ) : text == 1 ? (
                '非总价'
              ) : (
                '--'
              )
            ) : (
              <Select
                style={{ width: '100%' }}
                disabled={!isShowOpenBtn}
                defaultValue={record?.mpurchaseSourcePrepare?.quotationType || 0}
                value={text}
                onChange={(e) => onEditTable({ value: e, key: 'quotationType', type: 'Select', record, index })}
                options={[
                  {
                    value: 0,
                    label: '总价',
                  },
                  {
                    value: 1,
                    label: '非总价',
                  },
                ]}
              />
            )}
          </div>
        );
      },
    },
    {
      title: (
        <>
          <MyIcon type="icon-edit1" style={{ marginRight: '.5rem' }} />
          报价（元）
        </>
      ),
      dataIndex: 'sumInTax',
      key: 'sumInTax',
      width: 160,
      visible: true,
      render: (text: number | string, record: Record<string, any>, index) => {
        if (record?.quotationType === 1) {
          //|| record?.mpurchaseSourcePrepare?.quotationType === 1[这个数据是详情返回的，没有方法去改变他]
          return (
            <>
              {!isShowOpenBtn ? (
                ColumnsRenderFun({ text: record?.mpurchaseSourcePrepare?.sumInTaxText, isTooltip: true, wordNum: 200 })
              ) : (
                <Input.TextArea
                  rows={1}
                  placeholder="请输入报价"
                  disabled={!isShowOpenBtn}
                  allowClear
                  onChange={(e) => onEditTable({ value: e?.target.value, key: 'sumInTax', type: 'InputTextArea', record, index })}
                  defaultValue={record?.mpurchaseSourcePrepare?.sumInTaxText}
                />
              )}
            </>
          );
        } else {
          return (
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              {!isShowOpenBtn ? (
                formatDecimal(text)
              ) : (
                <InputNumber
                  disabled={!isShowOpenBtn}
                  bordered={true}
                  value={text}
                  defaultValue={'0.00'}
                  style={{ width: '100%' }}
                  placeholder="请输入报价"
                  min={0}
                  precision={2}
                  onChange={(value: any) => onEditTable({ value, key: 'sumInTax', type: 'InputNumber', record, index })}
                  onBlur={(val) => {
                    /** 如果val是空串，则给0.00字符串 */
                    if (val?.target?.value === '') onEditTable({ value: '0.00', key: 'sumInTax', type: 'InputNumber', record, index });
                  }}
                />
              )}
            </div>
          );
        }
      },
    },

    {
      // title: '投标文件',
      title: (
        <>
          <MyIcon type="icon-edit1" style={{ marginRight: '.5rem' }} />
          投标文件
        </>
      ),
      dataIndex: 'bidFileURL',
      key: 'bidFileURL',
      width: 230,
      visible: true,
      render: (text: string, record: Record<string, any>, index) => {
        if ((SourceState == LRKPB_STATE() || SourceState == CQXG_STATE()) && isShowOpenBtn) {
          return (
            <UploadFormCommon
              form={''}
              fileFormName={'bidFileURL'}
              spanCol={24}
              inRowProportion={24}
              name={'attachFile'}
              required={true}
              accept={'.doc|.docx|.pdf'}
              url={'/purchaseSourcePrepareController/uploadFile'}
              downloadUrl={'/purchaseSourcePrepareController/downloadFile'}
              fileFormDelName={'delLicenceUrl'}
              delFunc={() => {
                onEditTable({ value: null, key: 'bidFileURL', type: 'UploadFormCommon', record, index });
              }}
              uploadSuccessCallback={(url) => {
                onEditTable({ value: url, key: 'bidFileURL', type: 'UploadFormCommon', record, index });
              }}
              maxFile={1}
              isShowUploadBtn={true}
              fieldBusiPath={'purchase/prepare'}
              defaultFiles={record && record?.id && record?.['bidFileURL'] != '' ? record?.['bidFileURL'] : null}
              hintTitle={'如上传多个，只保留第一个！'}
            >
              上传
            </UploadFormCommon>
          );
        } else {
          if (record && record?.id && record?.['bidFileURL']) {
            return (
              <>
                {record?.['bidFileURL'] && splitFileUrl(record?.['bidFileURL']).length > 0
                  ? splitFileUrl(record?.['bidFileURL'])?.map((e, i) => {
                      return (
                        <Tooltip title={e.attachName} key={new Date().getTime() * 28451456254 + e?.attachName}>
                          <a
                            onClick={() => {
                              message.success('下载中，请稍后...');
                              downloadTemplate('/purchaseSourcePrepareController/downloadFile', e?.attachName, e?.attachUrl, () => {});
                            }}
                          >
                            <MyIcon type="icon-file-text-fill" />
                            &nbsp;
                            {getFileNameNotType(e.attachName, 8)}
                          </a>
                        </Tooltip>
                      );
                    })
                  : '--'}
              </>
            );
          } else {
            return '--';
          }
        }
      },
    },

    {
      // title: '质疑及处理材料',
      title: (
        <>
          <MyIcon type="icon-edit1" style={{ marginRight: '.5rem' }} />
          质疑及处理材料
        </>
      ),
      dataIndex: 'questioningMaterialsURL',
      key: 'questioningMaterialsURL',
      width: 230,
      visible: true,
      render: (text: string, record: Record<string, any>, index) => {
        if ((SourceState == LRKPB_STATE() || SourceState == CQXG_STATE()) && isShowOpenBtn) {
          return (
            <UploadFormCommon
              form={''}
              fileFormName={'questioningMaterialsURL'}
              spanCol={24}
              inRowProportion={24}
              name={'attachFile'}
              required={true}
              accept={'.doc|.docx|.pdf'}
              url={'/purchaseSourcePrepareController/uploadFile'}
              downloadUrl={'/purchaseSourcePrepareController/downloadFile'}
              fileFormDelName={'delLicenceUrl'}
              delFunc={() => {
                onEditTable({ value: null, key: 'questioningMaterialsURL', type: 'UploadFormCommon', record, index });
              }}
              uploadSuccessCallback={(url) => {
                onEditTable({ value: url, key: 'questioningMaterialsURL', type: 'UploadFormCommon', record, index });
              }}
              maxFile={1}
              isShowUploadBtn={true}
              fieldBusiPath={'purchase/prepare'}
              defaultFiles={record && record?.id && record?.['questioningMaterialsURL'] != '' ? record?.['questioningMaterialsURL'] : null}
              hintTitle={'如上传多个，只保留第一个！'}
            >
              上传
            </UploadFormCommon>
          );
        } else {
          if (record && record?.id && record?.['questioningMaterialsURL']) {
            return (
              <>
                {record?.['questioningMaterialsURL'] && splitFileUrl(record?.['questioningMaterialsURL']).length > 0
                  ? splitFileUrl(record?.['questioningMaterialsURL'])?.map((e, i) => {
                      return (
                        <Tooltip title={e.attachName} key={new Date().getTime() * 28451456254 + e?.attachName}>
                          <a
                            onClick={() => {
                              message.success('下载中，请稍后...');
                              downloadTemplate('/purchaseSourcePrepareController/downloadFile', e?.attachName, e?.attachUrl, () => {});
                            }}
                          >
                            <MyIcon type="icon-file-text-fill" />
                            &nbsp;
                            {getFileNameNotType(e.attachName, 8)}
                          </a>
                        </Tooltip>
                      );
                    })
                  : '--'}
              </>
            );
          } else {
            return '--';
          }
        }
      },
    },
    {
      // title: '投诉及处理材料',
      title: (
        <>
          <MyIcon type="icon-edit1" style={{ marginRight: '.5rem' }} />
          投诉及处理材料
        </>
      ),
      dataIndex: 'complaintMaterialsURL',
      key: 'complaintMaterialsURL',
      width: 230,
      visible: true,
      render: (text: string, record: Record<string, any>, index) => {
        if ((SourceState == LRKPB_STATE() || SourceState == CQXG_STATE()) && isShowOpenBtn) {
          return (
            <UploadFormCommon
              form={''}
              fileFormName={'complaintMaterialsURL'}
              spanCol={24}
              inRowProportion={24}
              name={'attachFile'}
              required={true}
              accept={'.doc|.docx|.pdf'}
              url={'/purchaseSourcePrepareController/uploadFile'}
              downloadUrl={'/purchaseSourcePrepareController/downloadFile'}
              fileFormDelName={'delLicenceUrl'}
              delFunc={() => {
                onEditTable({ value: null, key: 'complaintMaterialsURL', type: 'UploadFormCommon', record, index });
              }}
              uploadSuccessCallback={(url) => {
                onEditTable({ value: url, key: 'complaintMaterialsURL', type: 'UploadFormCommon', record, index });
              }}
              maxFile={1}
              isShowUploadBtn={true}
              fieldBusiPath={'purchase/prepare'}
              defaultFiles={record && record?.id && record?.['complaintMaterialsURL'] != '' ? record?.['complaintMaterialsURL'] : null}
              hintTitle={'如上传多个，只保留第一个！'}
            >
              上传
            </UploadFormCommon>
          );
        } else {
          if (record && record?.id && record?.['complaintMaterialsURL']) {
            return (
              <>
                {record?.['complaintMaterialsURL'] && splitFileUrl(record?.['complaintMaterialsURL']).length > 0
                  ? splitFileUrl(record?.['complaintMaterialsURL'])?.map((e, i) => {
                      return (
                        <Tooltip title={e.attachName} key={new Date().getTime() * 28451456254 + e?.attachName}>
                          <a
                            onClick={() => {
                              message.success('下载中，请稍后...');
                              downloadTemplate('/purchaseSourcePrepareController/downloadFile', e?.attachName, e?.attachUrl, () => {});
                            }}
                          >
                            <MyIcon type="icon-file-text-fill" />
                            &nbsp;
                            {getFileNameNotType(e.attachName, 8)}
                          </a>
                        </Tooltip>
                      );
                    })
                  : '--'}
              </>
            );
          } else {
            return '--';
          }
        }
      },
    },

    {
      title: (
        <div style={{ textAlign: 'center' }}>
          <Button type={'link'} size={'small'} icon={<PlusCircleOutlined />} className="manageBtntTxtStyle" onClick={onAdd}>
            添加
          </Button>
        </div>
      ),
      dataIndex: 'operation',
      key: 'operation',
      width: 160,
      visible: true,
      unDrag: true,
      fixed: 'right',
      render: (_: string, record: Record<string, any>, index: number) => {
        return (
          <div style={{ textAlign: 'center' }}>
            <Button
              danger
              type={'link'}
              size={'small'}
              className={'manageBtntTxtStyle manageColorRedBtn'}
              icon={<DeleteOutlined />}
              onClick={() => onDelete(index, record)}
            >
              删除
            </Button>
          </div>
        );
      },
    },
  ];

  if (isShowOpenBtn) {
    return columnsList;
  } else {
    return columnsList?.filter((item) => item?.key != 'operation');
  }
};

/**
 * @getSupplierBidTableColumns 评标委员会
 * @returns
 */
export const getSupplierBidTableColumns = ({ onOpen, onRemove }: any): Record<string, any>[] => {
  return [
    {
      title: '专家编号',
      dataIndex: 'id',
      key: 'id',
      visible: true,
      width: 150,
      fixed: 'left',
    },
    {
      title: '专家姓名',
      dataIndex: 'fullName',
      key: 'fullName',
      visible: true,
      width: 180,
      render: (text: string) => renderOverflowText(text),
    },
    {
      title: '专家类型',
      dataIndex: 'expertTypeName',
      key: 'expertTypeName',
      visible: true,
      width: 180,
      render: (text: string) => renderOverflowText(text),
    },
    {
      title: '专家级别',
      dataIndex: 'expertLevelName',
      key: 'expertLevelName',
      visible: true,
      width: 180,
      render: (text: string) => renderOverflowText(text),
    },
    {
      title: '行业类型',
      dataIndex: 'industryTypeName',
      key: 'industryTypeName',
      visible: true,
      width: 180,
      render: (text: string) => renderOverflowText(text),
    },
    {
      title: '政治面貌',
      dataIndex: 'politicalTypeName',
      key: 'politicalTypeName',
      visible: true,
      width: 180,
      render: (text: string) => renderOverflowText(text),
    },
    {
      title: '是否在岗',
      dataIndex: 'isDuty',
      key: 'isDuty',
      visible: true,
      width: 180,
      render: (text: string) => renderOverflowText(text),
    },
    {
      title: (
        <Button type={'link'} size={'small'} icon={<PlusCircleOutlined />} className="manageBtntTxtStyle" onClick={() => onOpen()}>
          选择
        </Button>
      ),
      dataIndex: 'operation',
      key: 'operation',
      width: 160,
      visible: true,
      unDrag: true,
      align: 'left',
      fixed: 'right',
      render: (_: string, __: Record<string, any>, index: number) => {
        return (
          <Button
            type={'link'}
            size={'small'}
            danger
            className={'manageBtntTxtStyle manageColorRedBtn'}
            icon={<DeleteOutlined />}
            onClick={() => {
              onRemove(index);
            }}
          >
            删除
          </Button>
        );
      },
    },
  ];
};
